export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * 判断是否是外部链接
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path)
  return isExternal
}

/**
 * 获取元素距离body顶部的距离
 */
export function getElementTop(el: HTMLElement) {
  // 获取当前元素距离最近开启定位(非static)的距离
  let parentTop = el.offsetTop
  // 获取元素offsetParent
  let current = el.offsetParent as HTMLElement
  // 进行判断是否是根元素(body)，如果不是进行offsetTop的计算累加
  while (current !== null) {
    parentTop += current.offsetTop
    current = current.offsetParent as HTMLElement
  }
  // 返回的累加高度就是该元素距离body顶部的距离
  return parentTop
}

export async function readAsText(data: any) {
  const reader = new FileReader()
  reader.readAsText(data)
  return new Promise((resolve, reject) => {
    reader.onload = () => resolve(reader.result)
    reader.onerror = () => reject(reader.error)
  })
}

export async function readAsArrayBuffer(data: any) {
  const reader = new FileReader()
  reader.readAsArrayBuffer(data)
  return new Promise((resolve, reject) => {
    reader.onload = () => resolve(reader.result)
    reader.onerror = () => reject(reader.error)
  })
}
